package com.cecil.generate.util;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期时间工具类
 */
@Slf4j
public class DateTimeUtil {

    public static final String DATE = "yyyy-MM-dd";
    public static final String TIME = "HH:mm:ss";
    public static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_TIME_MS = "yyyy-MM-dd HH:mm:ss:SSS";

    public static final String DATE_CN = "yyyy年MM月dd日";
    public static final String TIME_CN = "HH时mm分ss秒";
    public static final String DATE_TIME_CN = "yyyy年MM月dd日 HH时mm分ss秒";

    public static final String DATE_COMPACT = "yyyyMMdd";
    public static final String DATE_TIME_COMPACT = "yyyyMMddHHmmss";
    public static final String DATE_TIME_MS_COMPACT = "yyyyMMddHHmmssSSS";

    public static final String DATE_SLASH = "yyyy/MM/dd";


    /**
     * Date 转 LocalDateTime
     */
    public static LocalDateTime toLocalDateTime(Date d) {
        return LocalDateTime.ofInstant(d.toInstant(), ZoneId.systemDefault());
    }

    /**
     * LocalDateTime 转 Date
     */
    public static Date toDate(LocalDateTime ldt) {
        return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static String format(String pattern) {
        return format(LocalDateTime.now(), pattern);
    }

    public static String format(LocalDateTime now, String pattern) {
        if (now == null || pattern == null || pattern.trim().isEmpty()) {
            return "";
        }
        return DateTimeFormatter.ofPattern(pattern).format(now);
    }

    public static LocalDateTime parse(String datetime) {
        return parse(datetime, DATE_TIME);
    }

    public static LocalDateTime parse(String datetime, String pattern) {
        if (datetime == null || datetime.trim().isEmpty() || pattern == null || pattern.trim().isEmpty()) {
            return null;
        }
        return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern(pattern));
    }
}
